Skip to content

feat(lfs): serve cached batches when upstream fails - #90

Open
playit-coding-agent wants to merge 1 commit into
rolandjitsu:mainfrom
playit-coding-agent:lfs-batch-cache-fallback
Open

playit-coding-agent wants to merge 1 commit into
rolandjitsu:mainfrom
playit-coding-agent:lfs-batch-cache-fallback

Conversation

@playit-coding-agent

Copy link
Copy Markdown

What kind of change does this PR introduce?

  • fix
  • feat
  • refactor
  • perf
  • docs
  • test
  • build / ci
  • chore

Summary
When the upstream git-LFS batch call fails transiently (no response, or a
5xx such as GitHub's 504 during an LFS incident), the proxy returns 502 even
when every requested object is already in its cache, so CI fails although
nothing needs to be fetched.

The new opt-in --lfs-batch-cache-fallback answers such a download batch
from the cache when every requested object is cached: each gets the same
download action the normal path builds, so its GET is a plain cache hit. If
any object is not cached, the client does not offer the basic transfer, or
the request is malformed, the batch still fails with 502.

  • A 4xx is upstream's answer about the repo or credential and is never
    bypassed. That includes 429; treating it as final is deliberate.
  • Startup refuses the flag with --upstream-credential client or a
    github/gitlab/custom auth provider, where the upstream batch is part of
    the authorization check (see docs/security.md).
  • The batch failure is logged with its full error chain (URLs stripped), so
    the upstream status is visible.
  • New requests_total{kind="lfs_batch",result="cache_fallback"}.

Tests

  • Added / updated tests (unit, plus integration where it fits)
  • Not relevant, because: ...

Integration tests in tests/lfs.rs: fully cached on 504 (with a follow-up GET
that must not re-batch upstream), partly cached, unreachable upstream, nothing
cached, 4xx, malformed or non-basic requests, flag off. Unit test for the startup check.

Checklist

  • CI is green locally: cargo fmt --all --check, cargo clippy --all-targets --all-features --locked -- -D warnings, cargo test --all-features
  • Commits follow Conventional Commits; AI-assisted commits carry an Assisted-by: trailer (see CONTRIBUTING.md / AGENTS.md)
  • Preserves the read-only, pull-only invariant (no push or proactive replication to upstream)
  • Docs / README updated if behavior or flags changed

Breaking change?
No. The flag is off by default; behavior is unchanged without it.

A transient upstream batch failure (no response or a 5xx) failed the
client even when every requested object was cached. Behind
--lfs-batch-cache-fallback, answer such a download batch from the
cache. It is refused at startup where the upstream batch is part of
the authorization check.

Assisted-by: Claude:claude-opus-5-5
@loriopatrick

Copy link
Copy Markdown

Github's LFS is currently down so had our bot whip this up. I've manually reviewed, planning to run this fork for our CI to get around Github's LFS issues that are blocking us.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.21260% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 98.73%. Comparing base (93bb604) to head (62b6f1e).
⚠️ Report is 10 commits behind head on main.

Files with missing lines Patch % Lines
src/lfs.rs 98.30% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main      #90    +/-   ##
========================================
  Coverage   98.72%   98.73%            
========================================
  Files          10       10            
  Lines        6427     6544   +117     
========================================
+ Hits         6345     6461   +116     
- Misses         82       83     +1     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@rolandjitsu rolandjitsu left a comment •

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution. I left a few comments.

Also, please expose the flag in the helm chart as well. And let's use --lfs-serve-cached-on-error - it's longer, but more clear - and update to the same terminology where relevant.

And make sure codecov goes green - #90 (comment).

Comment thread src/server.rs
json
}
Err(e) => {
tracing::warn!(repo = %name, error = %format_args!("{e:#}"), "lfs batch failed");

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably move to the else branch - log only when fallback is unavailable or fails.

Or:

tracing::info!(repo = %name, error = %format_args!("{e:#}"), "upstream lfs batch failed;   
      served from cache");

Log that upstream failed, but it served from cache.

Comment thread docs/metrics.md
`upload_pack` (the packfile stream, timed to EOF).
- `result` on `requests_total`: `ok`, `error`, `upstream_error`, `unauthorized`,
`rejected`. On `upstream_ops_total`: `ok` or `error`. On `lfs_objects_total`:
`rejected`, `cache_fallback` (an `lfs_batch` answered from the cache after a

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
`rejected`, `cache_fallback` (an `lfs_batch` answered from the cache after a
`rejected`, `cached_on_error` (an `lfs_batch` answered from the cache after a

Comment thread src/main.rs
},
index.clone(),
)
.with_batch_cache_fallback(cfg.lfs_batch_cache_fallback),

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just pass this with the LfsConfig.

Comment thread src/lfs.rs
let resp = req
.send()
.await
.map_err(reqwest::Error::without_url)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could also define our own error type, e.g.:

#[derive(Debug)]                                                                             
pub enum UpstreamBatchError {                                                                
    Status(StatusCode),                                                                      
    Network(String),                                                                         
}

impl std::fmt::Display for UpstreamBatchError {                                              
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Status(code) => write!(f, "upstream batch status: {code}"),
            Self::Transport(msg) => write!(f, "upstream batch transport error: {msg}"),
        }
    }
}
                                                                                                 
impl std::error::Error for UpstreamBatchError {}

impl From<reqwest::Error> for UpstreamBatchError {                                           
    fn from(err: reqwest::Error) -> Self {
        // Strip the URL once here
        let err = err.without_url();
        match err.status() {
            Some(status) => Self::Status(status),
            None => Self::Transport(err.to_string()),
        }
    }
}

impl UpstreamBatchError {                                                                    
    pub fn is_transient(&self) -> bool {
        match self {
            Self::Status(status) => status.is_server_error(), // 5xx
            Self::Transport(_) => true, // connection failure, timeout, etc.
        }
    }
}

Then we can drop the mapping. This would be more idiomatic, though, more code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants